package me.maiz.tool.codegen.controller;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import me.maiz.tool.codegen.common.MD5Utils;
import me.maiz.tool.codegen.common.Result;
import me.maiz.tool.codegen.common.Tree;
import me.maiz.tool.codegen.domain.MenuDO;
import me.maiz.tool.codegen.domain.UserDO;
import me.maiz.tool.codegen.exceptions.AppException;
import me.maiz.tool.codegen.service.AppUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Controller
public class HomeController extends AdminBaseController{

    @Autowired
    private AppUserService userService;

    @GetMapping("/")
    public String toIndex(){
        return "login";
    }

    @PostMapping("login")
    @ResponseBody
    public Result login(String username, String password, HttpSession session){

        // 查询用户信息
        UserDO user = userService.findOneByKv("username",username);
        // 账号不存在
        if (user == null) {
            throw new AppException("账号或密码不正确");
        }
        // 密码错误
        if (!MD5Utils.encrypt(username,password).equals(user.getPassword())) {
            throw new AppException("账号或密码不正确");
        }
        // 账号锁定
        if (user.getStatus() == 0) {
            throw new AppException("账号已被锁定,请联系管理员");
        }

        session.setAttribute("sysUser",user);
        return Result.ok();
    }

    @GetMapping("/main")
    String main() {
        return "main";
    }

    @GetMapping({ "/index" })
    public String home(ModelMap modelMap){
        List<Tree<MenuDO>> menus = genStaticMenus();

        modelMap.put("menus",menus);
        return "index_v1";
    }

    private List<Tree<MenuDO>> genStaticMenus() {
        List<Tree<MenuDO>> menus = new ArrayList<>();
        // 商品管理
        Tree<MenuDO> m1 = new Tree<>();
        m1.setParentId("0");
        m1.setId("1");
        m1.setText("业务运营");
        m1.setAttributes(ImmutableMap.of("icon","fa fa-desktop"));

        Tree<MenuDO> c1 = new Tree<>();
        c1.setParentId("1");
        c1.setText("商品管理");
        c1.setAttributes(ImmutableMap.of("icon","fa fa-heartbeat","url","/codegen/productes"));

        Tree<MenuDO> c2 = new Tree<>();
        c2.setParentId("1");
        c2.setText("订单管理");
        c2.setAttributes(ImmutableMap.of("icon","fa fa-pie-chart","url","/codegen/order"));

        m1.setChildren(Arrays.asList(c1,c2));




        menus.add(m1);

        return menus;
    }

}
